package com.remoter.transport.socket.codec;

import java.io.ByteArrayOutputStream;

import com.remoter.basic.serialize.ISerialization;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author			koko
 * @date 			2017-08-09 09:22:56
 * @description 	类功能说明
 */
public class MessageEncoder extends MessageToByteEncoder<Object>{
	
	private ISerialization serialization;
	private Class<?> type;
	public MessageEncoder(ISerialization serialization,Class<?> type){
		this.serialization = serialization;
		this.type = type;
	}
	
	@Override
	protected void encode(ChannelHandlerContext ctx,Object msg, ByteBuf out)throws Exception{
		try(ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){
			this.serialization.serialize(msg,byteArrayOutputStream,this.type);
			byte[] body = byteArrayOutputStream.toByteArray();
			int dataLength = body.length;
	        out.writeInt(dataLength);
	        out.writeBytes(body);
		}
	}
	
}